#!/usr/local/bin/python
import sys
import os
import time
import re
from signal import signal, SIGINT

sys.path.append("/usr/local/oms")
sys.path.append("/usr/local/django")
os.environ["DJANGO_SETTINGS_MODULE"]="oms.settings"

from oms.apps.system import api as system_api
from oms.apps.system.models import Interface


def print_menu(options,exit_key="0",intro=""):
    print "\n\n"
    print intro
    print
    command = {}
    menu = []
    args = {} 
    for option in options:
        menu.append("%s. %s" % (option[0],option[1]))
        if len(option) > 2:
            command[option[0]] = option[2]
        else:
            command[option[0]] = None
        if len(option) > 3:
            args[option[0]] = option[3:]
            
    while True:
        print
        for line in menu: print line
        option = raw_input("\nChoose an option: ")
        if option == exit_key:
            break
        elif not option in command.keys():
            print "Unknown option %s" % option
        else:
            if args.has_key(option):
                command[option](*args[option])
            else:
                command[option]()

def print_web_urls():
    print
    urls = []
    for interface in system_api.get_interfaces():
        interface_ip = system_api.get_real_interface_ip(interface)
        if interface_ip:
            urls.append("http://%s/oms/" % interface_ip)
    if len(urls) >0:
        print "-"*30
        print "The web interface is available at:\n"
        for url in urls:
            print url  
        print "-"*30

def print_available_interfaces():
    interfaces = system_api.get_interfaces()
    if len(interfaces) > 0:
        print "Available network interfaces are: "
        for interface in interfaces:
            print interface
    else:
        print "No network interface detected"
        return


def input_interface(prompt="Interface name (Enter 0 to exit): "):
    interface = None
    while True:
        interface = raw_input(prompt)
        if not interface in system_api.get_interfaces():
            if interface == "0": break
            print "Wrong interface name: %s" % interface
            print_available_interfaces()
        else: break    
    return interface

def input_ip_address(prompt="Enter ip address (Enter 0 to exit): "):
    ip_regexp = r"^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$"
    ip = None
    while True:
        ip = raw_input(prompt)
        if not re.match(ip_regexp, ip):
            if ip == "0": break
            print "Wrong IP address: %s" % ip
        else:
            break
    return ip

def setup_dhcp(interface):
    print "Configuring DHCP for interface %s..." % interface
    db_interface = Interface.objects.get_or_create(name=interface)[0]
    db_interface.dhcp = True
    db_interface.save()
    system_api.set_interface(db_interface.name)
    print "done"
    print_web_urls()
    
def setup_static_ip(interface):
    ip = input_ip_address()
    netmask = input_ip_address("Enter netmask (Enter 0 to exit): ")
    
    print "Configuring static IP address for interface %s... " % interface 
    db_interface = Interface.objects.get_or_create(name=interface)[0]
    db_interface.dhcp = False
    db_interface.ip = ip
    db_interface.mask = netmask
    db_interface.save()
    system_api.set_interface(db_interface.name)
    print "done"
    print_web_urls()

def setup_interface():
    print_available_interfaces()
    interface = input_interface()
    if not interface: return
    INTERFACE_OPTIONS=(
            ("1","Setup DHCP",setup_dhcp,interface),
            ("2","Setup Static IP address",setup_static_ip,interface),
            ("0","Return"),
            )
    print_menu(INTERFACE_OPTIONS,intro="Configuring interface %s" % interface)


def change_root_password():
    print "Changing root password"
    os.system("passwd")            

def network_setup():
    NETWORK_OPTIONS=(
            ("1","Setup Interfaces",setup_interface),
            ("0","Return"),
            )
    print_menu(NETWORK_OPTIONS)

def run_shell():
    print "Exiting to shell...use CTRL+D or 'exit' command to return to the console menu\n"
    os.system("sh")

def handler(signal, frme):
    print "Exiting console menu...\n\n"
    sys.exit(0)

def system_reboot():
    print "System is rebooting, please wait..."
    os.system("reboot")

def system_halt():
    os.system("shutdown -p now")

if __name__ == "__main__":
    signal(SIGINT, handler)
    print_web_urls()
    MAIN_OPTIONS=(
            ("1","Network setup",network_setup),
            ("2","Change root password",change_root_password),
            ("3","Reboot system",system_reboot),
            ("4","Halt system",system_halt),
            ("0","Exit to shell",run_shell),
            )
    
    print_menu(MAIN_OPTIONS,exit_key=None)

